package br.edu.senai.converter;

import br.edu.senai.controller.CategoriaDAO;
import br.edu.senai.model.Categoria;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

@FacesConverter("categoriaConverter")
public class CategoriaConverter implements Converter {

    CategoriaDAO cDao = new CategoriaDAO();
    
    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        return (value != null && !value.isEmpty()) ? cDao.find(Integer.parseInt(value)) : null;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        try {
            Categoria categoria = (Categoria) value;
            return categoria.getId() != null ? String.valueOf(categoria.getId()) : null;
        } catch (Exception e) {
            e.getStackTrace();
        }
        return null;
    }    
}
